<template>
  <header class="main-header">
    <div class="logo-container">
      <div class="logo-wrapper">
        <img src="../../images/1.png" :alt="t('brand.name')" class="logo-image" />
        <span class="app-title">全球企业获客系统</span>
      </div>
    </div>
    
    <div class="header-controls">
      <!-- <router-link to="/" class="workspace-link">
        <el-icon><HomeFilled /></el-icon>
        <span><Translate keyName="nav.workstation" /></span>
      </router-link> -->
    </div>
    
    <div class="header-right">
      <div class="language-switch">
        <LanguageSelector />
      </div>
      
      <!-- 已登录状态显示用户信息 -->
      <div class="user-info" v-if="isLoggedIn">
        <el-dropdown trigger="hover" @command="handleCommand">
          <div class="avatar-container">
            <div class="avatar">L</div>
            <span class="username">{{ username }} <span class="member-tag" :class="`level-${memberLevel}`"><Translate :keyName="getMemberLevelKey(memberLevel)" /></span></span>
          </div>
          <template #dropdown>
            <el-dropdown-menu class="user-dropdown-menu">
              <div class="dropdown-header">
                <div class="dropdown-avatar">L</div>
                <div class="dropdown-user-info">
                  <div class="dropdown-username">{{ username }} 
                    <span class="member-tag" :class="`level-${memberLevel}`"><Translate :keyName="getMemberLevelKey(memberLevel)" /></span>
                  </div>
                  <div class="dropdown-account"><Translate keyName="user.account" /></div>
                </div>
              </div>
              
              <el-dropdown-item command="myExports">
                <i class="dropdown-icon export-icon"></i>
                <span><Translate keyName="user.myExports" /></span>
              </el-dropdown-item>
              
              <el-dropdown-item command="vipCenter">
                <i class="dropdown-icon vip-icon"></i>
                <span><Translate keyName="user.vipCenter" /></span>
              </el-dropdown-item>
              
              <el-dropdown-item command="myAccount">
                <i class="dropdown-icon account-icon"></i>
                <span><Translate keyName="user.myAccount" /></span>
              </el-dropdown-item>
              
              <el-dropdown-item command="promotion">
                <i class="dropdown-icon promotion-icon"></i>
                <span><Translate keyName="user.promotion" /></span>
              </el-dropdown-item>
              
              <el-dropdown-item command="profileSettings">
                <i class="dropdown-icon password-icon"></i>
                <span><Translate keyName="user.profileSettings" /></span>
              </el-dropdown-item>
              
              <el-dropdown-item divided command="logout">
                <i class="dropdown-icon logout-icon"></i>
                <span><Translate keyName="user.logout" /></span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      
      <!-- 未登录状态显示登录和注册按钮 -->
      <div class="auth-buttons" v-else>
        <el-button type="primary" size="small" @click="goToLogin"><Translate keyName="common.login" /></el-button>
        <el-button size="small" @click="goToRegister"><Translate keyName="common.register" /></el-button>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { logout } from '../api/auth'
import { getUserInfo, getUserBalanceInfo } from '../api/user'
import { ElMessage, ElButton } from 'element-plus'
import { CaretBottom, ArrowDown, Menu, HomeFilled } from '@element-plus/icons-vue'
import { t } from '../utils/i18n'
import { safeNavigate } from '../utils/router'
import { AUTH_EVENTS, dispatchAuthEvent } from '../utils/auth'
import LanguageSelector from '@/components/LanguageSelector.vue'
import Translate from '@/components/Translate.vue'

const router = useRouter()
const username = ref('LUOBO2880')
const isLoggedIn = ref(false)
const memberLevel = ref(0)

// 检查用户是否已登录
function checkLoginStatus() {
  const token = localStorage.getItem('token')
  isLoggedIn.value = !!token
  return isLoggedIn.value
}

// 获取用户信息
async function fetchUserInfo() {
  if (!isLoggedIn.value) return

  try {
    const res = await getUserInfo()
    if (res && res.code === 200 && res.data) {
      // 使用后端返回的用户名
      username.value = res.data.username || 'LUOBO2880'
    }
    
    // 获取用户余额信息（包含VIP等级）
    const balanceRes = await getUserBalanceInfo()
    if (balanceRes && balanceRes.code === 200 && balanceRes.data) {
      memberLevel.value = balanceRes.data.vipLevel || balanceRes.data.vip_level || 0
    }
  } catch (error) {
    // console.error('获取用户信息失败:', error)
    // 如果获取用户信息失败，可能是token无效，清除登录状态
    localStorage.removeItem('token')
    isLoggedIn.value = false
  }
}

// 处理登录事件
function handleLogin(event) {
  checkLoginStatus()
  if (isLoggedIn.value) {
    // 如果event中包含username，直接使用
    if (event.detail && event.detail.username) {
      username.value = event.detail.username
    } else {
      // 否则从后端获取用户信息
      fetchUserInfo()
    }
  }
}

// 处理登出事件
function handleLogout() {
  isLoggedIn.value = false
  username.value = ''
  memberLevel.value = 0
}

// 跳转到登录页面
function goToLogin() {
  router.push('/login')
}

// 跳转到注册页面
function goToRegister() {
  router.push('/register')
}

onMounted(async () => {
  // 初始检查登录状态
  checkLoginStatus()
  
  // 如果已登录，获取用户信息
  if (isLoggedIn.value) {
    await fetchUserInfo()
  } else {
    // console.log('用户未登录')
    ElMessage.warning(t('user.notLoggedIn'))
  }
  
  // 添加事件监听
  window.addEventListener(AUTH_EVENTS.LOGIN, handleLogin)
  window.addEventListener(AUTH_EVENTS.LOGOUT, handleLogout)
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener(AUTH_EVENTS.LOGIN, handleLogin)
  window.removeEventListener(AUTH_EVENTS.LOGOUT, handleLogout)
})

// 获取会员等级对应的翻译键
const getMemberLevelKey = (level) => {
  const levelKeyMap = {
    0: 'user.freeVersion',
    1: 'user.basicVip',
    2: 'user.advancedVip',
    3: 'user.premiumVip'
  }
  return levelKeyMap[level] || 'user.freeVersion'
}

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await logout()
      // 清除所有登录相关信息（包括 isFirstLogin 标记）
      const { clearAuthInfo } = await import('@/utils/auth')
      clearAuthInfo()
      isLoggedIn.value = false

      // 发送登出事件
      dispatchAuthEvent(AUTH_EVENTS.LOGOUT)

      // 显示成功消息
      ElMessage.success(t('user.logout'))

      // 直接跳转到登录页面
      setTimeout(() => {
        window.location.href = '/#/login'
      }, 500)
    } catch (error) {
      // console.error('退出登录失败:', error)
      ElMessage.error(t('user.logoutFailed'))
    }
  } else if (command === 'myExports') {
    router.push('/export-records')
  } else if (command === 'vipCenter') {
    // 跳转到个人中心的会员中心标签页
    router.push('/personal-center?tab=memberCenter')
  } else if (command === 'myAccount') {
    // 跳转到个人中心的我的账户标签页
    router.push('/personal-center?tab=myAccount')
  } else if (command === 'promotion') {
    // 跳转到个人中心的推广系统标签页
    router.push('/personal-center?tab=promotion')
  } else if (command === 'profileSettings') {
    // 跳转到个人中心的资料设置标签页
    router.push('/personal-center?tab=profileSettings')
  }
}
</script>

<style scoped>
.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  background-color: rgb(236, 245, 255);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: relative;
}

/* 确保图片和文字水平对齐 */
.logo-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  position: absolute;
  left: calc(120px / 1);
  transform: translateX(-50%);
  z-index: 10;
}

.logo-wrapper {
  display: flex;
  align-items: center; /* 确保图片和文字在同一水平线上 */
  gap: 12px; /* 控制图片和文字之间的间距 */
}

.logo-image {
  width: 48px;
  height: 48px;
  object-fit: contain;
  vertical-align: middle; /* 确保图片垂直居中 */
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a365d;
  letter-spacing: 0.5px;
  white-space: nowrap;
  line-height: 1; /* 确保文字行高与图片高度匹配 */
  display: inline-flex; /* 使用inline-flex确保对齐 */
  align-items: center; /* 垂直居中 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .logo-container {
    left: 20px;
    transform: none;
  }

  .logo-image {
    width: 40px;
    height: 40px;
  }

  .app-title {
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .app-title {
    font-size: 14px;
  }
}

.app-name {
  display: flex;
  flex-direction: column;
  line-height: 1.2;
}

.app-title {
  font-size: 18px;
  font-weight: 700;
  color: #1a365d;
  letter-spacing: 0.5px;
}

.app-subtitle {
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .logo-container {
    left: 20px;
    transform: none;
  }

  .logo-wrapper {
    padding: 6px 12px;
  }

  .logo-image {
    width: 40px;
    height: 40px;
  }

  .app-title {
    font-size: 16px;
  }

  .app-subtitle {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .logo-wrapper {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .app-name {
    margin-left: 0;
  }
}

.logo {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
  text-align: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.workspace-link {
  display: flex;
  align-items: center;
  color: #333;
  text-decoration: none;
  font-size: 14px;
}

.workspace-link .el-icon {
  margin-right: 5px;
}

.header-right {
  display: flex;
  align-items: center;
}

.language-switch {
  margin-right: 20px;
}

.language-dropdown {
  cursor: pointer;
  color: #333;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.user-info {
  position: relative;
}

.avatar-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #ff7171;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 8px;
}

.username {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.free-tag {
  background-color: #f0f9ff;
  color: #1890ff;
  font-size: 12px;
  padding: 2px 5px;
  border-radius: 4px;
  margin-left: 5px;
}

.member-tag {
  font-size: 12px;
  padding: 2px 5px;
  border-radius: 4px;
  margin-left: 5px;
}

.member-tag.level-0 {
  background-color: #f0f9ff;
  color: #1890ff;
}

.member-tag.level-1 {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.member-tag.level-2 {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.member-tag.level-3 {
  background-color: #fff2e8;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.user-dropdown-menu {
  min-width: 280px;
}

.dropdown-header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.dropdown-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ff7171;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.dropdown-user-info {
  flex: 1;
}

.dropdown-username {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.dropdown-account {
  font-size: 12px;
  color: #999;
}

.dropdown-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 8px;
  background-size: contain;
  background-repeat: no-repeat;
  vertical-align: middle;
}

.member-icon {
  background-image: url('../assets/icons/member.svg');
}

.export-icon {
  background-image: url('../assets/icons/export.svg');
}

.vip-icon {
  background-image: url('../assets/icons/vip.svg');
}

.account-icon {
  background-image: url('../assets/icons/account.svg');
}

.promotion-icon {
  background-image: url('../assets/icons/promotion.svg');
}

.password-icon {
  background-image: url('../assets/icons/password.svg');
}

.logout-icon {
  background-image: url('../assets/icons/logout.svg');
}

.auth-buttons {
  display: flex;
  gap: 10px;
}

.logo-image {
  max-width: 100%;
  height: auto;
  max-height: clamp(60px, 8vh, 120px); /* 响应式高度 */
}
</style> 